<template>
  <view class="game-space-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <view class="header-title-container">
        <i class="header-icon fas fa-gamepad"></i>
        <view>
          <h1 class="header-title">游戏空间</h1>
          <p class="header-subtitle">探索精彩游戏世界</p>
        </view>
      </view>
    </view>

    <!-- 游戏列表 -->
    <view class="games-grid">
      <view class="game-card" @tap="navigateToGame('snake')">
        <view class="game-icon bg-green-100 text-green-500">
          <i class="fa fa-gamepad text-4xl"></i>
        </view>
        <view class="game-info">
          <view class="game-name font-bold">贪吃蛇</view>
          <view class="game-online text-xs text-gray-500">在线 {{ gameStats.snake.online }} 人</view>
        </view>
      </view>

      <view class="game-card" @tap="navigateToGame('gomoku')">
        <view class="game-icon bg-blue-100 text-blue-500">
          <i class="fa fa-gamepad text-4xl"></i>
        </view>
        <view class="game-info">
          <view class="game-name font-bold">五子棋</view>
          <view class="game-online text-xs text-gray-500">在线 {{ gameStats.gomoku.online }} 人</view>
        </view>
      </view>

      <view class="game-card" @tap="navigateToGame('tictactoe')">
        <view class="game-icon bg-yellow-100 text-yellow-500">
          <i class="fa fa-gamepad text-4xl"></i>
        </view>
        <view class="game-info">
          <view class="game-name font-bold">井字棋</view>
          <view class="game-online text-xs text-gray-500">在线 {{ gameStats.tictactoe.online }} 人</view>
        </view>
      </view>

      <view class="game-card" @tap="navigateToGame('ruins')">
        <view class="game-icon bg-purple-100 text-purple-500">
          <i class="fa fa-monument text-4xl"></i>
        </view>
        <view class="game-info">
          <view class="game-name font-bold">遗迹探索</view>
          <view class="game-online text-xs text-gray-500">在线 {{ gameStats.ruins.online }} 人</view>
        </view>
      </view>

      <view class="game-card" @tap="navigateToGame('game')">
        <view class="game-icon bg-indigo-100 text-indigo-500">
          <i class="fa fa-tractor text-4xl"></i>
        </view>
        <view class="game-info">
          <view class="game-name font-bold">农场经营</view>
          <view class="game-online text-xs text-gray-500">在线 {{ gameStats.game.online }} 人</view>
        </view>
      </view>

      <view class="game-card" @tap="navigateToHtmlPage">
        <view class="game-icon bg-orange-100 text-orange-500">
          <i class="fa fa-file-code-o text-4xl"></i>
        </view>
        <view class="game-info">
          <view class="game-name font-bold">HTML 游戏</view>
          <view class="game-online text-xs text-gray-500">原生 HTML 页面</view>
        </view>
      </view>

      <view class="game-card" @tap="navigateToTestPage">
        <view class="game-icon bg-red-100 text-red-500">
          <i class="fa fa-flask text-4xl"></i>
        </view>
        <view class="game-info">
          <view class="game-name font-bold">测试页面</view>
          <view class="game-online text-xs text-gray-500">简单测试</view>
        </view>
      </view>

      <!-- 添加测试按钮 -->
      <view class="game-card" @tap="testRoomCreation">
        <view class="game-icon bg-gray-100 text-gray-500">
          <i class="fa fa-cog text-4xl"></i>
        </view>
        <view class="game-info">
          <view class="game-name font-bold">测试房间创建</view>
          <view class="game-online text-xs text-gray-500">验证流程</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { checkLoginStatus } from '@/utils/auth';
import { roomApi } from '@/api';
import { handleApiError } from '@/utils/error-handler';
import { useUserStore } from '@/stores/user';
import { getCurrentUserInfo } from '@/utils/auth'
import { createRoomListManager } from '@/utils/websocket-manager'
import { goToWebView } from '@/utils/navigation'

// 响应式数据
const gameStats = ref({
  snake: { online: 0, rooms: 0 },
  gomoku: { online: 0, rooms: 0 },
  tictactoe: { online: 0, rooms: 0 },
  ruins: { online: 0, rooms: 0 },
  game: { online: 0, rooms: 0 }
})

let wsManager = null

// 初始化WebSocket连接
const initWebSocket = () => {
  const userInfo = getCurrentUserInfo()
  if (!userInfo || !userInfo.userId) {
    console.error('用户信息为空，无法初始化WebSocket')
    return
  }

  // 移除WebSocket依赖，改为使用HTTP API获取房间统计
  getRoomStats()
}

// 获取房间统计信息
const getRoomStats = async () => {
  try {
    const res = await roomApi.getRooms()
    if (res && res.data) {
      updateGameStats(res.data)
    }
  } catch (error) {
    console.error('获取房间统计失败:', error)
  }
}

// 更新游戏统计信息
function updateGameStats(rooms) {
  if (!Array.isArray(rooms)) return

  // 重置统计
  const stats = {
    snake: { online: 0, rooms: 0 },
    gomoku: { online: 0, rooms: 0 },
    tictactoe: { online: 0, rooms: 0 },
    ruins: { online: 0, rooms: 0 },
    game: { online: 0, rooms: 0 }
  }

  // 统计每个游戏类型的房间和在线人数
  rooms.forEach(room => {
    const gameType = room.type || room.tag
    if (gameType && stats[gameType]) {
      stats[gameType].online += room.user_count || 0
      stats[gameType].rooms += 1
    }
  })

  gameStats.value = stats
  console.log('更新游戏统计:', stats)
}

// 页面挂载时初始化
onMounted(() => {
  if (checkLoginStatus()) {
    // 延迟获取房间统计，避免过早请求
    setTimeout(() => {
      getRoomStats()
    }, 1000)
  }
})

// 页面卸载时清理
onUnmounted(() => {
  // 移除WebSocket相关清理代码
})

/**
 * 导航到指定游戏
 * @param {string} gameName - 游戏名称
 */
async function navigateToGame(gameName) {
  // 检查登录状态
  if (!checkLoginStatus()) {
    uni.reLaunch({
      url: '/pages/login/login'
    });
    return;
  }

  try {
    const userInfo = getCurrentUserInfo();
    const userName = userInfo?.userName || '玩家1';
    const roomName = `${userName}的${getGameDisplayName(gameName)}房间`;
    
    // 创建房间
    const res = await roomApi.createRoom(
      roomName,
      gameName,
      '', // 无密码
      `欢迎来到${getGameDisplayName(gameName)}游戏！`, // 房间描述
      2, // 最大用户数
      undefined, // 无超时时间
      userInfo // 传递用户信息
    );
    
    const roomId = res.room_id || res.id || res.data?.room_id || res.data?.id;
    if (!roomId) {
      throw new Error('创建房间失败，未获取到房间ID');
    }
    
    // 加入房间
    await roomApi.joinRoom(roomId);
    
    // 保存房间ID到本地存储
    uni.setStorageSync('roomId', String(roomId));
    
    // 显示成功提示
    uni.showToast({
      title: '房间创建成功',
      icon: 'success',
      duration: 1000
    });
    
    // 跳转到游戏页面
    setTimeout(() => {
      if (gameName === 'ruins') {
        uni.navigateTo({
          url: '/pages/games/ruins/ruins'
        });
      } else if (gameName === 'game') {
        uni.navigateTo({
          url: '/pages/games/game/game'
        });
      } else {
        uni.navigateTo({
          url: `/pages/games/${gameName}/${gameName}`
        });
      }
    }, 1000);
    
  } catch (error) {
    console.error('创建房间失败:', error);
    handleApiError(error, '创建游戏房间');
    uni.showToast({
      title: '无法进入游戏',
      icon: 'none'
    });
  }
}

/**
 * 获取游戏显示名称
 * @param {string} gameName - 游戏名称
 */
function getGameDisplayName(gameName) {
  const gameNames = {
    'snake': '贪吃蛇',
    'gomoku': '五子棋',
    'tictactoe': '井字棋',
    'ruins': '遗迹探索',
    'game': '农场经营'
  };
  return gameNames[gameName] || gameName;
}

/**
 * 导航到 HTML 页面
 */
function navigateToHtmlPage() {
  // 检查登录状态
  if (!checkLoginStatus()) {
    uni.reLaunch({
      url: '/pages/login/login'
    });
    return;
  }

  // 跳转到 WebView 页面
  goToWebView('/static/html/index.html', 'HTML 游戏页面');
}

/**
 * 导航到测试页面
 */
function navigateToTestPage() {
  // 检查登录状态
  if (!checkLoginStatus()) {
    uni.reLaunch({
      url: '/pages/login/login'
    });
    return;
  }

  // 跳转到测试页面
  goToWebView('/static/html/test.html', '测试页面');
}

/**
 * 测试房间创建功能
 */
async function testRoomCreation() {
  // 检查登录状态
  if (!checkLoginStatus()) {
    uni.reLaunch({
      url: '/pages/login/login'
    });
    return;
  }

  try {
    const userInfo = getCurrentUserInfo();
    const userName = userInfo?.userName || '玩家1';
    const roomName = `${userName}的测试房间`;
    
    // 创建房间
    const res = await roomApi.createRoom(
      roomName,
      'gomoku', // 示例游戏类型
      '', // 无密码
      '这是一个测试房间，用于验证房间创建流程。',
      2, // 最大用户数
      undefined, // 无超时时间
      userInfo // 传递用户信息
    );
    
    const roomId = res.room_id || res.id || res.data?.room_id || res.data?.id;
    if (!roomId) {
      throw new Error('创建房间失败，未获取到房间ID');
    }
    
    // 加入房间
    await roomApi.joinRoom(roomId);
    
    // 保存房间ID到本地存储
    uni.setStorageSync('roomId', String(roomId));
    
    // 显示成功提示
    uni.showToast({
      title: '房间创建成功',
      icon: 'success',
      duration: 1000
    });
    
    // 跳转到游戏页面
    setTimeout(() => {
      uni.navigateTo({
        url: `/pages/games/gomoku/gomoku`
      });
    }, 1000);
    
  } catch (error) {
    console.error('测试房间创建失败:', error);
    handleApiError(error, '测试房间创建');
    uni.showToast({
      title: '无法进入游戏',
      icon: 'none'
    });
  }
}
</script>

<style scoped>
.game-space-container {
  padding: 20px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.page-header {
  margin-bottom: 32px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.header-title-container {
  display: flex;
  align-items: center;
}

.header-icon {
  font-size: 28px;
  color: #4096ff;
  margin-right: 12px;
  transition: transform 0.3s ease;
}

.header-title-container:hover .header-icon {
  transform: rotate(15deg);
}

.header-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 4px 0;
}

.header-subtitle {
  font-size: 14px;
  color: #64748b;
  margin: 0;
}

.games-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 24px;
}

.game-card {
  background: #ffffff;
  border-radius: 16px;
  padding: 24px 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border: 1px solid transparent;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.game-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.game-card:nth-child(1)::before { background-color: #10b981; }
.game-card:nth-child(2)::before { background-color: #3b82f6; }
.game-card:nth-child(3)::before { background-color: #f59e0b; }
.game-card:nth-child(4)::before { background-color: #8b5cf6; }
.game-card:nth-child(5)::before { background-color: #6366f1; }

.game-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 12px 20px rgba(0, 0, 0, 0.1);
  border-color: rgba(0, 0, 0, 0.05);
}

.game-card:hover::before {
  opacity: 1;
}

.game-icon {
  width: 72px;
  height: 72px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
  transition: transform 0.3s ease;
}

.game-card:hover .game-icon {
  transform: scale(1.1);
}

.game-icon.bg-green-100 {
  background-color: #ecfdf5;
}

.game-icon.bg-blue-100 {
  background-color: #eff6ff;
}

.game-icon.bg-yellow-100 {
  background-color: #fef3c7;
}

.game-icon.bg-purple-100 {
  background-color: #f3e8ff;
}

.game-icon.bg-indigo-100 {
  background-color: #e0e7ff;
}

.game-info {
  text-align: center;
  width: 100%;
}

.game-name {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 8px;
  transition: color 0.3s ease;
}

.game-card:hover .game-name {
  color: #4096ff;
}

.game-online {
  font-size: 13px;
  color: #94a3b8;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: auto;
}

.game-online::before {
  content: '●';
  font-size: 8px;
  margin-right: 6px;
  color: #10b981;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.4; }
  100% { opacity: 1; }
}

/* Empty state styles */
.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #64748b;
}

.empty-state-icon {
  font-size: 64px;
  margin-bottom: 20px;
  color: #d1d5db;
  transition: transform 0.3s ease;
}

.empty-state:hover .empty-state-icon {
  transform: rotate(-10deg) scale(1.1);
}

.empty-state p {
  margin-bottom: 24px;
  font-size: 16px;
}

.empty-state button {
  padding: 10px 20px;
  background-color: #4096ff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
}

.empty-state button:hover {
  background-color: #3182ce;
  transform: translateY(-2px);
}
</style>